var express = require('express');
const url = require("url");
const querystring = require("querystring");
var router = express.Router();
const https = require("http");

/* GET home page. */
router.get('/proxy_url', function (req, res, next) {
  const originUrl = url.parse(req.url);
  const qs = querystring.parse(originUrl.query);
  const targetUrl = qs["target"];
  const target = url.parse(targetUrl);

  const options = {
    hostname: target.hostname,
    port: 80,
    path: url.format(target),
    method: "GET",
    Cookie:'111111111111'
  };
  console.log(options);

  // 2.代发请求
  const proxy = https.request(options, _res => {
    // 3.修改响应头
    const resHeaders = {
      'content-encoding': 'br',
      'content-security-policy': "frame-ancestors *; worker-src 'self' blob:; script-src 'self' 'unsafe-inline' 'unsafe-eval' *.bytegoofy.com *.bytescm.com *.bytednsdoc.com *.snssdk.com *.bytedance.com",
      "content-type": "text/html; charset=utf-8",
      "date": "Wed, 18 May 2022 05:48:44 GMT",
      "eagleid": "6a3c48ac16528529239866863e",
      "server": "Tengine",
      "server-timing": "inner; dur=741",
      "server-timing": "cdn-cache;desc=MISS,edge;dur=27,origin;dur=786",
      "set-cookie": "ttwid=1%7CkC63rN_Iz0kYsBnWnFSJtLtX6Mugg1DHsN0v99ULb2w%7C1652062129%7Ccd56deb86b1a2926ba2afa56476c8fd7b659080ea487b94dc40617ae21540b72; Domain=.douyin.com; Path=/; Expires=Sat, 13 May 2023 05:48:44 GMT; HttpOnly; SameSite=None; Secure=true",
      "timing-allow-origin": "*",
      "vary": "Accept-Encoding",
      "via": "cache39.l2cn1850[786,0], vcache30.cn2982[813,0]",
      "x-content-type-options": "nosniff",
      "x-download-options": "noopen",
      "x-tt-logid": "20220518113832010158031138240C6E4E",
      "x-tt-trace-host": "014d1fdc951017db77c9d1523e77dfda1cf5af684145f4ef2b856b9a25df56267e6c2bd225d2ce2bc34193f8cc2f9c0b437015c4fd7f3d956967562545f971c441a7ba6c48fc16336e7caeb62ceb2f7ec1601afdc444e963a4f54478c975d3680b5b1e0333572d592aef9b529d6fc75d12",
      "x-tt-trace-tag": "id=03;cdn-cache=miss;type=dyn",
      "x-xss-protection": "1; mode=block",
      "x-frame-options":"content-security-policy"
    }
    for (const key in resHeaders) {
      const val = resHeaders[key];
      res.setHeader(key, val);

    }
    _res.pipe(res, {
      end: true
    });
  });
  console.log(proxy.getHeaders());
  req.pipe(proxy, {
    end: true
  });
});

router.get('/test', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;
